ComponentOne PdfViewer for UWP
Opening Potentially Protected Files
Task-Based Help > Opening Potentially Protected Files

When giving the end-user the ability to open a PDF file, sometimes you can’t predict whether or not the file will be password protected or not. The following sample method demonstrates how to perform this check and open the document accordingly.

Visual Basic
Copy Code
' open an existing PDF file
Private Sub _btnOpen_Click(sender As Object, e As RoutedEventArgs)
Dim dlg = New OpenFileDialog()
dlg.Filter = "Pdf files (*.pdf)|*.pdf"
If dlg.ShowDialog().Value
Then Dim ms = New System.IO.MemoryStream()
Using stream = dlg.File.OpenRead()
stream.CopyTo(ms)
End Using LoadProtectedDocument(ms, Nothing)
End If
End Sub

 

C#
Copy Code
// open an existing PDF file
void _btnOpen_Click(object sender, RoutedEventArgs e)
{
var dlg = new OpenFileDialog();
dlg.Filter = "Pdf files (*.pdf)|*.pdf";
if (dlg.ShowDialog().Value)
 {
  var ms = new System.IO.MemoryStream();
  using (var stream = dlg.File.OpenRead())
   {
     stream.CopyTo(ms);
   }
   LoadProtectedDocument(ms, null);
  }
}

If a protected file is attempted to be read, then we will call the LoadProtectedDocument method. Calling this method with null for a password will open unprotected files. If the file is password-protected (encrypted), an Exception will be thrown and caught. The user will then be prompted for the actual password and the method will call itself recursively.

Visual Basic
Copy Code
' loads password-protected Pdf documents.
 Private Sub LoadProtectedDocument(stream As System.IO.MemoryStream, password As String)
 Try
 stream.Position = 0
 _viewer.LoadDocument(stream, password)
 Catch x As Exception
 'if (x.Message.IndexOf("password") > -1)
 '{
 Dim msg = "This file seems to be password-protected." & vbCr & vbLf & "Please provide the password and try again." C1.Silverlight.C1PromptBox.Show(msg, "Enter Password", Function(text, result)
 If result = MessageBoxResult.OK Then
 ' try again using the password provided by the user
 LoadProtectedDocument(stream, text)
 End If
'}
'else
'{
' throw;
'}
End Function)
End Try
End Sub

 

C#
Copy Code
// loads password-protected Pdf documents.
void LoadProtectedDocument(System.IO.MemoryStream stream, string password)
   {
    try
    {
     stream.Position = 0;
     _viewer.LoadDocument(stream, password);
   } 
   catch (Exception x)
   {
     //if (x.Message.IndexOf("password") > -1)
     //{
        var msg = "This file seems to be password-protected.\r\nPlease provide the password and try again.";
        C1.Silverlight.C1PromptBox.Show(msg, "Enter Password", (text, result) =>
          {
          if (result == MessageBoxResult.OK)
          {
           // try again using the password provided by the user
           LoadProtectedDocument(stream, text);
          }
       });
    //}
   //else
   //{
    // throw;
   //}
   }
}